package com.ibeetl.admin.console.web;

import com.ibeetl.admin.console.service.DictConsoleService;
import com.ibeetl.cms.web.query.CatalogQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreFile;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.rbac.tree.CatalogItem;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.AnnotationUtil;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.ParamUtil;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.CmsCatalog;
import com.ibeetl.cms.service.CmsCatalogDictService;
import com.ibeetl.cms.service.CmsCatalogService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author lijiazhi
 */
@Controller
public class CatalogController {


    private static final String MODEL = "/admin/catalog";
    private final Log log = LogFactory.getLog(this.getClass());


    @Autowired
    private CmsCatalogService catalogService;

    @Autowired
    CorePlatformService platformService;
    @Autowired
    private DictConsoleService dictConsoleService;
    @Autowired
    CmsCatalogDictService catalogDictService;
    @Autowired
    FileService fileService;
    /*页面*/
    
    @GetMapping(MODEL + "/index.do")
    @Function("admin.catalog")
    public ModelAndView index() {
		ModelAndView view = new ModelAndView("/admin/catalog/index.html");
		view.addObject("search", CatalogQuery.class.getName());
        return view;
    }
    
    @GetMapping(MODEL + "/add.do")
    @Function("admin.catalog.add")
    public ModelAndView add() {
   	 ModelAndView view = new ModelAndView("/admin/catalog/edit.html");
   	 return view;
    }
    @GetMapping(MODEL + "/edit.do")
    @Function("admin.catalog.edit")
    public ModelAndView edit(Long id) {
   	 ModelAndView view = new ModelAndView("/admin/catalog/edit.html");
   	 CmsCatalog catalog = catalogService.queryById(id);
     view.addObject("catalog", catalog);
   	 return view;
    }
    
    /*Json*/
    
    /**
     * 查询
     * @return
     */
    @PostMapping(MODEL + "/list/condition.json")
    @Function("admin.catalog.query")
    @ResponseBody
    public JsonResult condition() {
    	   List<Map<String, Object>> list = AnnotationUtil.getInstance().getAnnotations(Query.class, CatalogQuery.class);
       return JsonResult.success(list);
    }
    
    
    @PostMapping(MODEL + "/list.json")
    @Function("admin.catalog.query")
    @ResponseBody
    public JsonResult<PageQuery> list(CatalogQuery condtion) {
        PageQuery page = condtion.getPageQuery();
        catalogService.queryByCondtion(page);
        return JsonResult.success(page);
    }
    

    /**
     * 添加
     * @param catalog
     * @return
     */
    @PostMapping(MODEL + "/add.json")
    @Function("admin.catalog.add")
    @ResponseBody
    public JsonResult save(CmsCatalog catalog, HttpServletRequest request) {
        return saveOrUpdateCatalog(catalog,request);
    }

    /**
     * 更新
     * @return
     */
    @PostMapping(MODEL + "/update.json")
    @Function("admin.catalog.edit")
    @ResponseBody
    public JsonResult edit(CmsCatalog catalog, HttpServletRequest request) {
    	return saveOrUpdateCatalog(catalog,request);
    }

    private JsonResult saveOrUpdateCatalog(CmsCatalog cmsCatalog, HttpServletRequest request) {
        CmsCatalog catalogDb = catalogService.queryById(cmsCatalog.getId());

        if (cmsCatalog.getId() != null && StringUtils.isNotBlank(cmsCatalog.getCode())) {
            CmsCatalog catalog1 = this.catalogService.getCatalogByCode(cmsCatalog.getCode());
            if (catalog1 != null && catalog1.getId().longValue() != cmsCatalog.getId().longValue()) {
                return JsonResult.failMessage("保存失败，栏目代码不能重复");
            }
        }

        if (catalogDb == null) catalogDb = new CmsCatalog();
        catalogDb = ParamUtil.initParameterObj(request, catalogDb);

        //保存附件的标题和链接
        String[] attachmentIds = request.getParameterValues("attachment-id[]");
        if (attachmentIds != null) {
            for (String attachmentId : attachmentIds) {
                CoreFile attachment = this.fileService.getCoreFileById(NumberUtils.toLong(attachmentId));
                String title = request.getParameter("attachment-title-" + attachmentId);
                String url = request.getParameter("attachment-url-" + attachmentId);
                attachment.setTitle(title);
                attachment.setUrl(url);
                this.fileService.updateCoreFile(attachment);
            }
        }

        //保存图片的标题和链接
        String[] imageIds = request.getParameterValues("image-id[]");
        if (imageIds != null) {
            for (String imageId : imageIds) {
                CoreFile image = this.fileService.getCoreFileById(NumberUtils.toLong(imageId));
                String title = request.getParameter("image-title-" + imageId);
                String url = request.getParameter("image-url-" + imageId);
                image.setTitle(title);
                image.setUrl(url);
                this.fileService.updateCoreFile(image);
            }
        }

        String[] positions = request.getParameterValues("positions[]");//传来的参数是用jquery.ajax封装的，对checkbox的参数，会自动增加[]两个字符
        String positionParamValue = request.getParameter("positions");
        String position = org.apache.tomcat.util.buf.StringUtils.join(positions) + (positionParamValue!=null?positionParamValue:"");//如果checkbox组件中，直选中一个，jquery.ajax只会传positions的参数，只能使用getParameter获得，所以这里要考虑到只选择一个checkbox的情况
        catalogDb.setPosition(position);

        int success = catalogService.upsert(catalogDb);
        //处理栏目位置
        updateDict(catalogDb.getId(), position);
        if (success > 0) {
            this.platformService.clearCatalogCache();
            return new JsonResult().success(catalogDb.getId());
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 根据id查询栏目信息
     * @param id 栏目Id
     * @return
     */
    @PostMapping(MODEL + "/view.json")
    @Function("admin.catalog.query")
    @ResponseBody
    public JsonResult<CmsCatalog> view(Long id) {
    	
        CmsCatalog fun = catalogService.queryById(id);
        CatalogItem root =  this.platformService.buildCatalog();
        CatalogItem child =  root.findChild(fun.getId());
        CmsCatalog parent = child.getParent().getData();
        fun.set("parentCatalogName", parent.getName());
        return JsonResult.success(fun);
    }

    /**
     * 删除
     * @param id 栏目id
     * @return
     */
    @PostMapping(MODEL + "/delete.json")
    @Function("admin.catalog.delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        catalogService.deleteCatalog(id);
        return new JsonResult().success();
    }
    
    /**
     * 批量删除
     * @param ids 栏目id集合
     * @return
     */
    @PostMapping(MODEL + "/batchDel.json")
    @Function("admin.catalog")
    @ResponseBody
    public JsonResult delete(String ids) {
    	List<Long> dels = ConvertUtil.str2longs(ids);
    	catalogService.batchDeleteCatalogId(dels);
    	return new JsonResult().success();
    }
    
    public JsonResult updateDict(Long catalogId, String ids) {
        List<Long> all = ConvertUtil.str2longs(ids);
        List<Long> addIds = new ArrayList<Long>();
        List<Long> delIds = new ArrayList<Long>();
        List<Long> dbs = catalogDictService.getDictIdByCatalog(catalogId);
        Iterator<Long> it = all.iterator();
        for(Long id:all) {
            if(!dbs.contains(id)) {
                addIds.add(id);
            }
        }
        
        for(Long id:dbs) {
            if(!all.contains(id)) {
                delIds.add(id);
            }
        }
        dictConsoleService.updateCatalogDict(catalogId, addIds, delIds);
        return JsonResult.success();
    }
}


